# _*_ coding utf-8 _*_
# george
# time: 2025/1/11下午12:43
# name: user.py
# comment:
from common.database import db_connection
from sqlalchemy import Table, select, and_
from model.role import Role
from model.team import Team
import logging

db_session, Base, engine = db_connection()

user_logger = logging.getLogger("User的数据库log:")


class User(Base):
    # 表结构的反射加载
    __table__ = Table("user", Base.metadata, autoload_with=engine)

    # 用户登陆验证
    def login_verify(self, username, password):
        sql = select(User).where(and_(username == User.username, password == User.password))
        result = db_session.execute(sql).scalar()
        return result

    # 获取所有用户
    def get_all_users(self):
        result = db_session.query(User, Team.team_name, Role.role_name) \
            .outerjoin(Team, User.team_id == Team.id). \
            outerjoin(Role, User.role_id == Role.id).order_by(User.id).all()
        return result

    # 改变用户状态exist | not exist
    def change_user_status(self, id, status):
        result = db_session.query(User).where(User.id == id).first()
        try:
            if result:
                result.user_exit = status  # 设置为True，因为SQL中1通常表示True
                db_session.commit()  # 提交事务
                user_logger.debug(f"修改user:{result.username}状态成功!!")
                return True
            else:
                user_logger.debug(f"修改:{result.username}状态失败!!")
                return False
        except Exception as e:
            db_session.rollback()
            db_session.flush()
            user_logger.debug(f"修改:{result.username}状态失败:{e}!!")
            return False

    # 添加用户
    def add_user(self, job_n, username, password, team_id, role_id):
        try:
            new_user = User()
            new_user.job_n = job_n
            new_user.username = username
            new_user.password = password
            new_user.team_id = team_id
            new_user.role_id = role_id
            new_user.user_exit = 1
            db_session.add(new_user)
            db_session.commit()
            user_logger.debug(f"添加用户:{job_n}成功!!")
            return True
        except Exception as e:
            db_session.rollback()
            db_session.flush()
            user_logger.debug(f"添加用户:{job_n}失败{e}!!")
            return False

    # 删除用户
    def drop_user(self, user_id):
        user_to_delete = db_session.query(User).filter(User.id == user_id).first()
        try:
            if user_to_delete:
                db_session.delete(user_to_delete)
                db_session.commit()
                user_logger.debug(f"删除用户{user_to_delete.username}成功!!")
                return True
            else:
                db_session.rollback()
                user_logger.debug(f"未找到用户{user_to_delete.username}的用户!!")
            return False
        except Exception as e:
            user_logger.debug(f"删除用户:{user_to_delete.username}失败:{e}")
            return False

    # 编辑用户
    def update_user(self,user_id,username,job_n, password, team_id, role_id):
        try:
            user = db_session.query(User).filter(User.id == user_id).first()
            if user:
                user.job_n = job_n
                user.username = username
                if password:  # Only update password if provided
                    user.password = password
                user.team_id = team_id
                user.role_id = role_id
                db_session.commit()
                user_logger.debug(f"编辑用户{username}成功!!")
                return True
            else:
                user_logger.debug(f"未找到用户{username}!!")
                return False
        except Exception as e:
            db_session.rollback()
            db_session.flush() 
            user_logger.debug(f"编辑用户{username}失败:{e}!!")
            return False

    # 获取用户信息
    def get_user_info(self, user_id):
        try:
            user = db_session.query(User).filter(User.id == user_id).first()
            if user:
                user_logger.debug(f"获取用户{user.username}信息成功!!")
                return user
            else:
                user_logger.debug(f"未找到ID为{user_id}的用户!!")
                return None
        except Exception as e:
            user_logger.debug(f"获取用户信息失败:{e}!!")
            return None
